package bar.dark.lee.manager.money;

import java.util.HashMap;

import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.EditTextInputFilter;

public class BankBookInsertActivity extends SuperActivity
{
	private DBSQLite sql;
	
	private RadioButton radioButton1;
	private RadioButton radioButton2;
	
	private EditText nameEditText;
	private EditText moneyEditText;
	
	private Button minusButton;
	
	private Button insertButton;
	private Button cancelButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setContentView(R.layout.bankbook_insert);
		
		setGoneTipButton();
		
		setTitle("통장 추가");
		
		setFindView();
		setOnClickListener();
		setData();
	}
	
	private void setFindView()
	{
		radioButton1 = (RadioButton) findViewById(R.id.bankBookInsertRadio1);
		radioButton2 = (RadioButton) findViewById(R.id.bankBookInsertRadio2);
		
		nameEditText = (EditText) findViewById(R.id.bankbookInsertName);
		moneyEditText = (EditText) findViewById(R.id.bankbookInsertMoney);
		EditTextInputFilter.filteringMoneyEditText(moneyEditText);
		
		minusButton = (Button) findViewById(R.id.bankBookMinusButton);
		
		insertButton = (Button) findViewById(R.id.bankBookInsertButton);
		cancelButton = (Button) findViewById(R.id.bankBookCancelButton);
	}

	private void setOnClickListener()
	{
		minusButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				moneyEditText.setText("-");
				
				try {
					moneyEditText.setSelection(
							BDUtil.getCommaDel(moneyEditText.getText().toString()).length());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (nameEditText.getText().toString().equals("") 
						|| nameEditText.getText().toString().length() < 1)
				{
					BDUtil.showToast(superContext, "통장 이름을 입력해주세요.");
					return;
				}
				
				if (BDUtil.getCommaDel(moneyEditText.getText().toString()).equals("") 
						|| BDUtil.getCommaDel(moneyEditText.getText().toString()).equals("-") 
						|| BDUtil.getCommaDel(moneyEditText.getText().toString()).length() < 1)
				{
					BDUtil.showToast(superContext, "금액을 제대로 입력해주세요.");
					return;
				}
				
				boolean nameOverlap = BDUtil.getOverlapCheck(sql, superContext, 
						"SELECT name FROM bankbook WHERE name = '" + 
						BDUtil.getApostrophe(nameEditText.getText().toString()) + "';");
				
				if (nameOverlap)
				{
					BDUtil.showDialog(superContext, "확인", "동일한 통장 이름이 존재 합니다.");
					nameEditText.setText("");
					return;
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 1);
			}
		});
		
		cancelButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				onBackPressed();
			}
		});
	}

	private void setData()
	{
	}
	
	private void setBankBookData()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		String name = nameEditText.getText().toString();
		map.put("name", name);
		map.put("money", BDUtil.getCommaDel(moneyEditText.getText().toString()));
		
		// 통장 테이블에 데이터를 셋팅한디.
		sql.insert(BankBookInsertActivity.this, map, "bankbook");
		
		sql.selectMapTile(this, "SELECT id FROM bankbook WHERE name = '" + BDUtil.getApostrophe(name) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				
				int id = -1;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					c.moveToNext();
				}
				
				if (id > -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("name", nameEditText.getText().toString());
					map.put("linkid", id + "");
					map.put("count", "999");
					
					if (radioButton1.isChecked())
					{
						map.put("addflag", "0");
					}
					else
					{
						map.put("addflag", "1");
					}
					
					// 세부 통장 테이블에 데이터를 셋팅한디.
					sql.insert(BankBookInsertActivity.this, map, "bankbook_detail");
				}
			}
		});
	}

	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(BankBookInsertActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 1)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setBankBookData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				
				return arg0[0];
				
			} else 
				return arg0[0];
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialogFinish(BankBookInsertActivity.this, "추가완료", "통장이 추가 되었습니다.");
			}
		}
	}
	
	@Override
	protected void tipButton()
	{
	}
}
